/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.hilo.boot.core.dubbo;

import com.alibaba.dubbo.rpc.*;
import com.alibaba.dubbo.rpc.service.GenericService;
import org.jretty.apibase.MsgBase;
import org.hilo.boot.core.UT;
import org.hilo.boot.core.util.HiloStackTraceFilter;
import org.jretty.log.LogFactory;

/**
 * Custom Exception Filter of Consumer side.
 * 
 * @author zollty
 * @since 2018-05-10
 */
//@Activate(group = Constants.CONSUMER)
public class ConsumerMainFilter extends AbstractFilterService implements Filter {
    protected boolean traceAll;
    
    public ConsumerMainFilter() {
        super(LogFactory.getLogger("Dubbo_Consumer_Filter_Log"));
    }

    /**
     * @see ProviderMainFilter#invoke(Invoker, Invocation)
     * 
     * 核心设计：
     *      Dubbo任何运行时异常不外抛，都以Result API形式返回；
     *      任何业务异常也不外抛，都以Result API形式返回；
     *  
     * 日志设计：
     *      除I18n这种明确定义的异常，其他的任何异常均在filter处自动记录日志，Result API仅返回对应的errorCode和简单msg信息。
     *      在Provider端和Consumer端都要记录异常，包括Dubbo任何运行时异常以及非I18n定义的业务异常。
     *      
     * TraceLog设计：
     *      TraceLog是对以上日志设计的补充，除了上面的异常日志，还要记录I18n定义的异常，以及成功返回的Result信息。
     */
    @Override
    public Result invoke(Invoker<?> invoker, Invocation inv) {
        Long startTime = System.currentTimeMillis();
        String remoteHost = invoker.getUrl().getHost();
        Result result;
        try {
            result = invoker.invoke(inv);
        } catch (RuntimeException ex) {
            handleException(invoker, inv, remoteHost, startTime, ex);
            throw ex;
        }
        if (GenericService.class == invoker.getInterface()) {
            return result;
        }
        // provider filter将所有Exception都已封装到Result data里面，所以此处hasException()大概率为false
        // 但是如果对方没有使用标准provider filter，那么此处可能是业务异常。
        if (result.hasException()) {
            handleException(invoker, inv, remoteHost, startTime, result.getException());
        }
        if (handleServiceResult(invoker, inv, remoteHost, startTime, result)) {
            if(traceAll) {
                traceNormal(invoker, inv, remoteHost, startTime, result);
            }
            recordMetricsSuccess(true, invoker, inv, remoteHost, startTime);
        }
        return result;
    }
    
    public void handleException(Invoker<?> invoker, Invocation inv, String remoteHost,
            Long startTime, Throwable ex) {
        String code;
        if (ex instanceof RpcException) {
            code = DubboStatus.getByException((RpcException) ex).name();
        } else {
            code = DubboStatus.UNKNOWN.name();
        }
        recordMetrics(invoker, inv, remoteHost, startTime, DubboStatus.DUBBO_ERROR, code);
        
        String key = UT.Excp.getExceptionSign(ex);
        checkAndLog(invoker, inv, remoteHost, startTime, key, code, ex);
    }
    
    public boolean handleServiceResult(Invoker<?> invoker, Invocation inv, String remoteHost, Long startTime,
            Result result) {
        if (result.getValue() instanceof org.jretty.apibase.Result) {
            org.jretty.apibase.Result<?> svcResult = (org.jretty.apibase.Result<?>) result.getValue();
            if (svcResult.isFailed()) {
                // 业务异常
                String code = svcResult.getCode();
                if (UT.Str.isNullOrEmpty(code)) {
                    code = MsgBase.UNDEFINED_ERR.name();
                }
                recordMetrics(invoker, inv, remoteHost, startTime, DubboStatus.BIZ_ERROR, code);

                // 使用Result API返回异常，大概率使用了标准Provider Filter，所以此处检查是否有error标志
                if (svcResult.get("error") != null) {
                    // 未捕获异常
                    checkAndLog(invoker, inv, remoteHost, startTime, code, code, new RpcException(svcResult.getMessage()));

                } else if (traceAll) {
                    traceException(invoker, inv, remoteHost, startTime, code, svcResult.getMessage());
                }
                return false;
            }
        }
        return true;
    }
    
    /**
     * 记录异常日志 如果最近5秒内有这个相同的异常，则不再记录。5秒钟后，重新计时。
     */
    protected void checkAndLog(Invoker<?> invoker, Invocation inv, String remoteHost, Long startTime, String key,
            String code, Throwable ex) {
        if (cache.putIfAbsent(key, code)) {
            StringBuilder sn = assembleBaseInfo(invoker, inv, remoteHost, startTime).insert(0, "error: ")
                    .append(": \r\n").append(code).append(": ")
                    .append(UT.Excp.getStackTraceStr(HiloStackTraceFilter.me(), ex));

            log.error(sn.toString());
        }
    }

    protected void recordMetrics(Invoker<?> invoker, Invocation inv, String remoteHost, long start,
            String outcome, String errorCode) {
        super.recordMetrics(true, invoker, inv, remoteHost, start, outcome, errorCode);
    }

}
